package com.wst.wst_server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wst.wst_server.entity.LoginUser;
import com.wst.wst_server.entity.User;
import com.wst.wst_server.mapper.UserMapper;
import com.wst.wst_server.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据username去数据库查询
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name",username));
        if(user==null)
            throw new RuntimeException("该用户不存在");
        //2 TODO:2. 查询用户的权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<String> menus = userMapper.getMenusByUserid(user.getId());
        for(String menu : menus){
            authorities.add(new SimpleGrantedAuthority(menu));
        }
        //3.返回UserDetails，包括用户信息和权限信息
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        loginUser.setAuthorities(authorities);
        return loginUser;
    }
}
